/**
 * Created by hjqi on 2016/6/8.
 */
module.controller('ServiceOperatorNavController',
    function($scope, $rootScope,$state, $stateParams, $http,k8sService){
        //console.log( "$stateParams.currtab--->"+ JSON.stringify($stateParams) ) ;
        $scope.curImg = undefined;
        $scope.createEvt = {};
        $scope.myPromise = undefined;
        $scope.templateUrl = '/template/cp/ngbusytemplate.html';
        //$scope.ngbusy = {promise:$scope.myPromise,message:'creating service....'}
        //default set service create controller
        $scope.serviceController = 'ServiceCreateController';
        $scope.op = 'create';

        var _deregistry_upd_svc_st = undefined;

        $scope.modal = {};
        $scope.modal.steps = [
            {num:1,title:'选择镜像'},
            {num:2,title:'创建服务'}
        ];
        $scope.modal.step = 0;

        $scope.autoScalerEntity = {max: 5};

        $scope.isFirstStep = function () {
            return $scope.modal.step === 0;
        };

        $scope.isLastStep = function () {
            return $scope.modal.step === ($scope.modal.steps.length - 1);
        };

        $scope.isCurrentStep = function (step) {
            return $scope.modal.step === step;
        };

        $scope.setCurrentStep = function (step) {
            if(!$scope.lockStep)
                $scope.modal.step = step;
        };

        $scope.getCurrentStep = function () {
            return $scope.modal.steps[$scope.modal.step].num;
        };

        $scope.getNextLabel = function () {
            var _lastLabel = '添加';
            if($scope.op === 'update')
                _lastLabel = '更新';
            return ($scope.isLastStep()) ? _lastLabel : '下一步';
        };

        $scope.handlePrevious = function () {
            if(!$scope.lockStep){
                if($scope.isFirstStep())
                    $state.go('cp.service');
                else
                    $scope.modal.step -= 1;
            }
        };

        $scope.handleNext = function () {
            if ($scope.isLastStep()) {
                //need to create service and go back to service page
                //$scope.ok();
                var _svc = $scope.updatingService;
                if($scope.op === 'create' || isServiceInMidStatus(_svc) === false){

                    //fix status in dbjson
                    //$scope.updatingService.dbJson.totalStatue = $scope.updatingService.totalStatue;

                    angular.element(".spinner")
                        .fadeIn("fast")
                        .delay(1000000)
                        .fadeOut('slow', function() {
                            //

                        });
                    $scope.$broadcast('submit');
                }else{
                    alertify.error('need to wait previous operator finished');
                }

            } else {
                //下一步 or 添加、更新
                $scope.modal.step += 1;
                $scope.currtab =  $stateParams.currtab ;
               // console.log( "currtab--->"+$stateParams.currtab) ;
                //当前已经是最后一步更新了

            }
        };

        $scope.selectImg = function(item){
            $scope.curImg = item;
            $scope.handleNext();
        }

        var initService = function() {
            //deploy through image market
            if (selectedImage || updatingService) {

                //trigger load images service
                if (selectedImage)
                    $scope.curImg = selectedImage;
                else if (updatingService) {
                    $scope.volumeType= updatingService.dbJson.volumeType ; //assign the volume type of pod e.g:glusterfs ,hostPath
                    $scope.op = 'update';
                    $scope.modal.steps[1].title = '更新服务';
                    $scope.updatingService = updatingService;
                }
                //set crate form page
                $scope.setCurrentStep(1);
                //lock the page and not allow to switch
                $scope.lockStep = true;
                //add class create_table_ul
                $scope.tabcls = 'create_table_ul';
                $scope.licls = 'create_table_li';
                if ($scope.op === 'update') {
                    $scope.autoScalerEntity = {
                        scaleName: updatingService.id,     //自动伸缩组件名称（自定义）
                        max: 5,                      //能够伸缩最大pod数目
                        min: 1,                     //至少需要的pod数目
                        refKind: (updatingService.dbJson.rc)?updatingService.dbJson.rc.kind : updatingService.dbJson.petset.kid, //基于组件进行控制伸缩（ReplicationController  ReplicationController Deploment）
                        refName: (updatingService.dbJson.rc)?updatingService.dbJson.rc.metadata.name : updatingService.dbJson.petset.metadata.name,   //组件名称
                        cpuPct: 5,                   //cpu使用率百分比[0-100],-1表示取默认值80
                        clusterId: updatingService.dbJson.node.clusterId             //集群id
                    };
                    k8sService.findPodAutoScale({scaleName: updatingService.id}, updatingService.dbJson.node.clusterId).then(function (result) {
                        result = result.data;
                        $scope.autoScalerEntityPrev = $scope.autoScalerEntity = {
                            scaleName: updatingService.id,     //自动伸缩组件名称（自定义）
                            max: result.maxReplicas,                      //能够伸缩最大pod数目
                            min: result.minReplicas,                     //至少需要的pod数目
                            refKind: result.scaleTargetRef.kind, //基于组件进行控制伸缩（ReplicationController  ReplicationController Deploment）
                            refName: result.scaleTargetRef.name,   //组件名称
                            cpuPct: result.targetCPUUtilizationPercentage,                   //cpu使用率百分比[0-100],-1表示取默认值80
                            clusterId: updatingService.dbJson.node.clusterId             //集群id
                        };//结果的处理
                        $scope.autoScalerEnabled = $scope.autoScalerEnabledTarget = true;
                    }, function (err) {
                        $scope.autoScalerEnabled = $scope.autoScalerEnabledTarget = false;
                        //结果的处理
                    });
                }
            }
        }

        var selectedImage = null;
        if ($stateParams.imageName && $stateParams.isMarket) {
            selectedImage = {
                name: $stateParams.imageName,
                isMarket: $stateParams.isMarket
            }
            initService();
        } else {
            var updatingService = null;
            if ($stateParams.service) {
                console.log('/cp/service/update/gee:volumeType='+ JSON.stringify( $stateParams.service.dbJson.volumeType ) ) ;
                updatingService = $stateParams.service;
                initService();
            } else if ($stateParams.serviceName) {
                var serviceName = $stateParams.serviceName;
                k8sService.getServices(serviceName).then(function (result) {
                    if (result.data.length === 0)
                        alertify.alert('服务不存在', serviceName);
                    else {
                        updatingService = result.data[0];
                        //查询伸缩组件
                        initService();
                    }
                }, function (err) {
                    alertify.alert('query applications err', ret.data);
                });
            }
        }

        $scope.$watch('createEvt',function(_new,_old){
            if(_new !== undefined){
                $scope.myPromise = _new.promise;
            }
        },true);

        _deregistry_upd_svc_st = $rootScope.$on('updateServiceStatus',function(event,service){
            if($scope.updatingService !==undefined && $scope.updatingService.app === service.app){
                $scope.updatingService.dbJson.totalStatue = service.totalStatue;
                $scope.updatingService.totalStatue = service.totalStatue;
            }
        });

        function isServiceInMidStatus(service){
            return  ( service.totalStatue === "starting" || service.totalStatue === "restarting" || service.totalStatue === "stoping");
        }

        $scope.$on('$destroy', function(){

            //unsubscribe event
            if(_deregistry_upd_svc_st !== undefined)
                _deregistry_upd_svc_st();

        });
});